const DY = {
    runBaseTime:1200000,
    packName: 'com.ss.android.ugc.aweme',
    endTime:'',
    startTime:'',
    scrollView:0,
    deviceW:0,
    deviceH:0,
    taskThred:null,
    taskStart:false,
    init(){
        myUi.setTopText(App.getDate() + ': ' + "正在启动抖音...")
        let time = new Date().getTime();
        this.startTime = time;
        this.endTime = time + parseInt(this.runBaseTime);
        this.scrollView = 0;
        this.deviceW = device.width;
        this.deviceH = device.height;
        this.startTask()
    },
    startTask(){
        let openFlage = App.launchApp(this.packName);
        let tryTask  = 0 
        sleep(3000)
        let page = depth(21).id('4mm').exists()
        while (!page && tryTask < 5) {
            // 按下返回键
            home()
            toast('未检测到进入抖音软件，尝试重新进入');
            sleep(1000)
            tryTask += 1
            App.launchApp(this.packName);
            sleep(2000)
            page = depth(21).id('4mm').exists()
        }
        
        if(tryTask >= 5){
            toast('请手动重新打开抖音，并重启脚本')
            return
        }
        myUi.setTopText(App.getDate() + ': ' + "开始执行抖音任务,任务将持续20分钟,请不要干预屏幕...")
        this.taskThred = threads.start(
            function () {
                DY.viewTask()
            }
        )
    },
    viewTask(){        
        let w = this.deviceW
        let h = this.deviceH
        swipe(w/2,h* 0.7 ,w/2,h*0.1,500)
        while(new Date().getTime() < this.endTime) {
            console.log('当前任务配置数据：' + JSON.stringify(DY) + '\n');
            this.scrollView += 1
            App.randomSleep(3,30)
            swipe(w/2,h* 0.7 ,w/2,h*0.1,500)
        }
         myUi.setTopText(App.getDate() + ': ' + "抖音20分钟浏览完成，可手动点击关闭返回...")
    },
    clearTask() {
        if (this.taskThred && this.taskThred.isAlive()) {
            this.taskThred.interrupt()
        } else {
            log('当前任务已结束，无需清除')
        }
        DY.taskStart = false
    },
}
module.exports = DY